/**
 * Copyright (C) 2018-2021
 * All rights reserved, Designed By www.yixiang.co
 * 注意：本软件为www.yixiang.co开发研制
 */
package co.yixiang.app.modular.shop.controller;

import cn.hutool.core.util.StrUtil;
import co.yixiang.app.common.persistence.dao.StoreOrderMapper;
import co.yixiang.app.common.persistence.model.*;
import co.yixiang.app.modular.shop.service.ICateService;
import co.yixiang.app.modular.shop.service.IGoodsService;
import co.yixiang.app.modular.shop.service.IOrderService;
import co.yixiang.app.modular.shop.service.dto.*;
import co.yixiang.app.modular.shop.service.impl.OrderGoodsServiceImpl;
import co.yixiang.app.modular.shop.service.mapper.OrderGoodsMapper;
import co.yixiang.app.modular.shop.service.vo.*;
import co.yixiang.app.common.R;
import co.yixiang.app.common.persistence.model.StoreSpecGoodsPrice;
import co.yixiang.app.modular.shop.service.ICateService;
import co.yixiang.app.modular.shop.service.IGoodsService;
import co.yixiang.app.modular.shop.service.IOrderService;
import co.yixiang.app.modular.shop.service.dto.CateDTO;
import co.yixiang.app.modular.shop.service.dto.GoodsDTO;
import co.yixiang.app.modular.shop.service.dto.SpecItemDTO;
import co.yixiang.app.modular.shop.service.mapper.GoodsMapper;
import co.yixiang.app.modular.shop.service.vo.CartVO;
import co.yixiang.app.modular.shop.service.vo.CollectVO;
import co.yixiang.app.modular.shop.service.vo.OrderVo;
import co.yixiang.app.modular.shop.service.vo.PageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.shaun.core.annotation.HasRole;
import com.baomidou.shaun.core.context.ProfileHolder;
import com.baomidou.shaun.core.profile.TokenProfile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.beans.Transient;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName MallController
 * @Author hupeng <610796224@qq.com>
 * @Date 2019/9/8
 **/

@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(value = "商城模块", tags = "商城模块", description = "商城模块")
@CrossOrigin
public class MallController {
    private final ICateService cateService;
    private final IGoodsService goodsService;
    private final GoodsMapper goodsMapper;
    private final IOrderService orderervice;

    private final OrderGoodsServiceImpl orderGoodsService;

    private final OrderGoodsMapper orderGoodsMapper;


    @GetMapping("/shop/mall-lists")
    @ApiOperation(value = "商品分类模块列表",notes = "商品分类模块列表")
    public R lists(@RequestParam(value = "page",defaultValue = "0") int page,
                   @RequestParam(value = "limit",defaultValue = "10") int limit){
        //int userId = userOperator.getUser().getId();
        int userId = 0;
        List<CateDTO> goodsCates = cateService.getList();
        List<GoodsDTO> recommedGoods = goodsService.getList(0,
                page,limit,userId,"",1);
        List<GoodsDTO> newGoods = goodsService.getList(0,page,limit,userId,"",2);

        List<GoodsDTO> collectGoods = goodsMapper.toDto(goodsService.collectGoods(page,limit,userId));

        Map<String,Object> map = new HashMap<>();
        map.put("goodsCates",goodsCates);
        map.put("recommedGoods",recommedGoods);
        map.put("newGoods",newGoods);
        map.put("collectGoods",collectGoods);
        return R.success(map);
    }


    @GetMapping("/shop/getgoodsCates")
    @CrossOrigin
    @ApiOperation(value = "查询商品类别信息",notes = "查询商品类别信息")
    public R getgoodsCates(@RequestParam(value="type") Long type,@RequestParam(value="state") Long state){
        ArrayList<CateDTO> objects = new ArrayList<>();
        List<CateDTO> list = cateService.getList();

        for (CateDTO c:list ) {
            if (type==0){
                if (c.getPid()==type){
                    if (state==1){
                        List<CateDTO> childsList = c.getChildsList();
                        for (CateDTO c1:childsList) {
                            objects.add(c1);
                        }
                    }else {
                        objects.add(c);
                    }

//
                }
            }else {
                if (c.getId()==type){
                    List<CateDTO> childsList = c.getChildsList();
                    for (CateDTO c1:childsList) {
                        objects.add(c1);
                    }
                }
            }
        }
//        for (CateDTO c:objects) {
//            System.out.println("查询商品类别信息 objects= "+c);
//
//        }

        HashMap<String,Object> map = new HashMap<>();
        map.put("goodsCates",objects);
        return R.success(map);
    }


    @GetMapping("/shop/mall-goods-list")
    @ApiOperation(value = "获取商品列表",notes = "获取商品列表")
    public R goodsList(@RequestParam(value = "page",defaultValue = "0") int page,
                       @RequestParam(value = "page_num",defaultValue = "10") int limit,
                       @RequestParam(value = "cat_id",defaultValue = "0") int catId,
                       @RequestParam(value = "keywords",defaultValue = "") String keywords){

        int userId = 0;
        List<GoodsDTO> goods = goodsService.getList(catId,page,
                limit,userId,keywords,0);
        for (GoodsDTO g:goods) {
            System.out.println("GoodsDTO  " +g);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",goods);
        return R.success(map);
    }
//    原自带查询商品信息的接口
//    @HasRole("user_role")
//    @GetMapping("/shop/mall-goods-detail")
//    @ApiOperation(value = "商品详情",notes = "商品详情")
//    public R goodsDetail(@RequestParam(value = "goods_id",defaultValue = "0") int goodsId){
//        int userId = 0;
//        Map<String, StoreSpecGoodsPrice> specPrice = goodsService.goodsSpecPrice(goodsId);
//        GoodsDTO goodsDetail = goodsMapper.toDto(goodsService.getById(goodsId));
//        Map<String, List<SpecItemDTO>> specs = goodsService.goodsSpec(goodsId);
//
//        boolean isCollect = goodsService.isCollect(goodsId,userId);
//
//        Map<String,Object> map = new HashMap<>();
//        map.put("detail",goodsDetail);
//        map.put("spec_price",specPrice);
//        map.put("specs",specs);
//        map.put("isCollect",isCollect);
//        return R.success(map);
//    }

    @HasRole("user_role")
    @GetMapping("/shop/mall-goods-detail")
    @ApiOperation(value = "商品详情",notes = "商品详情")
    public R goodsDetail(@RequestParam(value = "goods_id",defaultValue = "0") int goodsId){

        int userId = 0;


        GoodsDetailDTO goodsDetail=goodsService.goodsSpecItem(goodsId);



        Map<String,Object> map = new HashMap<>();
        map.put("detail",goodsDetail);
        map.put("spec_price",goodsDetail.getSpecItemDTO());
        map.put("images_price",goodsDetail.getImageUrls());
        return R.success(map);
    }

    @HasRole("user_role")
    @PostMapping("/shop/getMallGoods")
    @ApiOperation(value = "查询符合要求的商品",notes = "商品详情")
    public R getMallGoods(@Validated @RequestBody StoreGoods s){
        Map<String,Object> map = new HashMap<>();

        if (s.getGoodsName().trim().equals("")){
            List<StoreGoods> goodsList = goodsService.list(new QueryWrapper<StoreGoods>()
                    .like("goods_name", s.getGoodsName())
                    .eq("is_new",s.getIsNew())
                    .eq("is_recommend",s.getIsRecommend()));
            map.put("goodsList",goodsList);
        }
        return R.success(map);
    }

    @HasRole("user_role")
    @PostMapping("/shop/getMallGoodsIs")
    @ApiOperation(value = "查询符合要求的商品",notes = "商品详情")
    public R getMallGoodsIs(){
        Map<String,Object> map = new HashMap<>();

            List<StoreGoods> goodsRecommendList = goodsService.list(new QueryWrapper<StoreGoods>()
                    .eq("is_recommend",1));
        List<StoreGoods> goodsNewList = goodsService.list(new QueryWrapper<StoreGoods>()
                .eq("is_new",1));
        map.put("goodsNewList",goodsNewList);
        map.put("goodsRecommendList",goodsRecommendList);

        return R.success(map);
    }
    @HasRole("user_role")
    @PostMapping("/shop/mall-add-collect")
    @ApiOperation(value = "添加商品收藏",notes = "添加商品收藏")
    public R addCollect(@Validated @RequestBody CollectVO collectVO){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        boolean result = goodsService.addOrCancelCollect(collectVO.getGoodsId(),userId,1);

        if(result){
            return R.success("操作成功");
        }else{
            return R.error(4000,"操作失败");
        }
    }

    @HasRole("user_role")
    @PostMapping("/shop/mall-cancel-collect")
    @ApiOperation(value = "取消商品收藏",notes = "取消商品收藏")
    public R cancelCollect(@Validated @RequestBody CollectVO collectVO){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());

        boolean result = goodsService.addOrCancelCollect(collectVO.getGoodsId(),userId,2);
        if(result){
            return R.success("操作成功");
        }else{
            return R.error(4000,"操作失败");
        }
    }

    @HasRole("user_role")
    @PostMapping("/shop/mall-add-cart")
    @ApiOperation(value = "添加购物车",notes = "添加购物车")
    public R addCart(@Validated @RequestBody CartVOs cartVO){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());

        boolean result = goodsService.addCart(cartVO,userId);
        if(result){
            return R.success("操作成功");
        }else{
            return R.error(4000,"操作失败");
        }

    }

    @HasRole("user_role")
    @GetMapping("/shop/mall-cart-del")
    @ApiOperation(value = "删除购物车",notes = "删除购物车")
    public R delCart(@RequestParam(value = "goods_ids",defaultValue = "") String goodsIds){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        if(StrUtil.isEmpty(goodsIds)){
            return R.error(4000,"参数缺失");
        }
        boolean result = goodsService.delCart(goodsIds,userId);
        if(result){
            return R.success("操作成功");
        }else{
            return R.error(4000,"操作失败");
        }

    }

    @HasRole("user_role")
    @GetMapping("/shop/mall-cart-list")
    @ApiOperation(value = "获取购物车列表",notes = "获取购物车列表")
    public R cartList(@RequestParam(value = "page",defaultValue = "0") int page,
                      @RequestParam(value = "page_num",defaultValue = "10") int limit){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        PageVO pageVO = new PageVO();
        pageVO.setPage(page);
        pageVO.setLimit(limit);
        List<StoreCart> storeCarts = goodsService.cartList(pageVO, userId);
        List<StoreCartVo> storeCartVos = new ArrayList<StoreCartVo>();
        for (StoreCart s:storeCarts) {
            StoreCartVo storeCartVo = new StoreCartVo();
            BeanUtils.copyProperties(s,storeCartVo);
            if (s.getSelected()==1){
                storeCartVo.setFlag(true);
            }else {
                storeCartVo.setFlag(false);
            }
            storeCartVos.add(storeCartVo);
        }
        return R.success(storeCartVos);
    }

    @HasRole("user_role")
    @PostMapping("/shop/mall-order-submit1223")
    @ApiOperation(value = "提交订单",notes = "提交订单")
    public R submit1223(@Validated @RequestBody OrderVo orderVo){
        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        String orderSn = "";
        if(Integer.valueOf(orderVo.getOrderFrom()) == 1){
            orderSn = orderervice.addOrderOfOne(orderVo,userId);
        }else{
            orderSn = orderervice.addOrderOfTwo(orderVo,userId);
        }

        HashMap<String,String> map = new HashMap<>();
        map.put("order_no",orderSn);
        return R.success(map);
    }

    @HasRole("user_role")
    @PostMapping("/shop/mall-order-submit")
    @ApiOperation(value = "单个商品提交订单",notes = "单个商品提交订单")
    public R submitOrder(@Validated @RequestBody OrderVoPo orderVoPo ){


        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        SimpleDateFormat dmDate = new SimpleDateFormat("yyyyMMddHHmmss"); // 获取当前时间

        Random random = new Random(); // 定义随机数
        int ran = random.nextInt(1000000); // 随机数长度位数

        Date date = new Date();
        String dateran = dmDate.format(date);
        String randomMath = "DD"+dateran+ran;

        System.out.println(randomMath);
        orderVoPo.setOrderSn(randomMath);
        if(!(userId>0)){
            userId=2;
        }
        orderVoPo.setUserId(userId);
        System.out.println("提交订单信息"+orderVoPo.getGoodsId());
        System.out.println("提交订单信息"+orderVoPo.getAddress());
        System.out.println("提交订单信息"+orderVoPo.getInvoiceTitle());
        String orderSn = "";
        boolean save = orderervice.save(orderVoPo);
        StoreOrder order_sn = orderervice.getOne(new QueryWrapper<StoreOrder>().eq("Order_sn", randomMath));
        StoreGoods byId = goodsService.getById(orderVoPo.getGoodsId());
        StoreOrderGoods storeOrderGoods = new StoreOrderGoods();

        storeOrderGoods.setOrderId(order_sn.getOrderId());
        storeOrderGoods.setGoodsName(byId.getGoodsName());
        storeOrderGoods.setGoodsId(orderVoPo.getGoodsId());
        storeOrderGoods.setGoodsLogo(byId.getGoodsLogo());
        storeOrderGoods.setSpecKeyName("规格："+orderVoPo.getZipcode());
        System.out.println("保存订单商品前输出  +++ "+storeOrderGoods);
        boolean save1 = orderGoodsService.save(storeOrderGoods);

//      int i = orderervice.addOrderMy(orderVoPo);
        String id=String.valueOf(orderVoPo.getOrderId());
        HashMap<String,String> map = new HashMap<>();
        map.put("order_no",id);
        return R.success(map);
    }
    @HasRole("user_role")
    @PostMapping("/shop/mall-orderCart-submit")
    @ApiOperation(value = "购物车提交订单",notes = "购物车提交订单")
    public R submitOrderCart(@Validated @RequestBody OrderVoCart orderVoPo){


        TokenProfile profile = ProfileHolder.getProfile();
        int userId =  Integer.valueOf(profile.getId());
        SimpleDateFormat dmDate = new SimpleDateFormat("yyyyMMddHHmmss"); // 获取当前时间

        Random random = new Random(); // 定义随机数
        int ran = random.nextInt(1000000); // 随机数长度位数

        Date date = new Date();
        String dateran = dmDate.format(date);
        String randomMath = "DD"+dateran+ran;

        System.out.println(randomMath);
        orderVoPo.setOrderSn(randomMath);
        if(!(userId>0)){
            userId=2;
        }
        orderVoPo.setUserId(userId);
        //System.out.println("提交订单信息"+orderVoPo.getGoodsId());
        System.out.println("提交订单信息"+orderVoPo.getAddress());
        System.out.println("提交订单信息"+orderVoPo.getInvoiceTitle());
        String orderSn = "";
        boolean save = orderervice.save(orderVoPo);
        StoreOrder order_sn = orderervice.getOne(new QueryWrapper<StoreOrder>().eq("Order_sn", randomMath));
        List<StoreOrderGoods> storeGoods = orderVoPo.getStoreGoods();
        for (StoreOrderGoods s:storeGoods) {
            s.setOrderId(order_sn.getOrderId());
            s.setSpecKeyName("规格："+s.getSpecKey());
            System.out.println("保存订单商品前输出  +++ "+s);
            boolean save1 = orderGoodsService.save(s);
        }


//      int i = orderervice.addOrderMy(orderVoPo);
        String id=String.valueOf(orderVoPo.getOrderId());
        HashMap<String,String> map = new HashMap<>();
        map.put("order_no",id);
        return R.success(map);
       // return R.success("成功");
    }

    /**
     * 查询订单主列表
     */
    @HasRole("user_role")
    @GetMapping("/orderList")
    @ApiOperation(value = "获取用户下的订单列表",notes = "获取用户下的订单列表")
    public R list(int status,int userId)
    {
        HashMap<String,String> map = new HashMap<>();

        TokenProfile profile = ProfileHolder.getProfile();
         userId =  Integer.valueOf(profile.getId());
        if(!(userId>0)){
            userId=2;
        }
        List<OrderDTO> list = orderervice.orderList(status, userId,0,20);
        System.out.println(new Date().toString()+"获取到该用户在"+status +" 的订单量为 "+list.size());
        List<OrderDTO> orderDTOS = new ArrayList<>();
        for (OrderDTO s:list) {

//            System.out.println("订单信息 "+s.getGoodsList() + s.getOrderId());
            System.out.println("订单信息 "+s.getGoodsList()+s.getOrderId() );
            if (s.getPayStatus().equals(0)){
                s.setExamine("unpaid");
            }else if (s.getPayStatus().equals(1)&&s.getShippingStatus().equals(0)&&s.getOrderStatus().equals(0)){
                s.setExamine("back");
            }else if (s.getShippingStatus().equals(1)){
                s.setExamine("unreceived");
            }else if (s.getOrderStatus().equals(1)){
                s.setExamine("received");
            } else if (s.getShippingStatus().equals(2)||s.getShippingStatus().equals(3)){
                s.setExamine("refunds");
            }

            orderDTOS.add(s);


        }


        return R.success(orderDTOS);
    }


}
